<template>

    <div class="app-container" v-if="canList">
        <div class="filter-container">

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="课程名"
                      v-model="listQuery.name">
            </el-input>

            <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                       v-model="listQuery.status"
                       placeholder="状态">
                <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item" :value="index">
                </el-option>
            </el-select>


            <div style="display: inline-block">

                <el-button style="margin-left: 10px;" class="filter-item" type="primary" v-waves icon="el-icon-search"
                           @click="handleFilter">查找
                </el-button>
                <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"
                           v-if="canSave" icon="el-icon-edit">添加
                </el-button>
                <!--                <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"-->
                <!--                           @click="handleDownload">导出-->
                <!--                </el-button>-->
            </div>
        </div>

        <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
                  style="width: 100%;min-height:1000px;">
            <el-table-column align="center" label="序号">
                <template slot-scope="scope">
                    <span>{{scope.$index+1}}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column align="center" label="课程ID">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.goodsId}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column align="center" label="省">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.province}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column align="center" label="市">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.city}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column align="center" label="县">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.county}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column align="center" label="详细地址">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.detail}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column align="center" label="课程名">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column align="center" label="开课人数">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.number}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column align="center" label="备注">
                <template slot-scope="scope">
                    <span>{{scope.row.remark}}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column align="center" label="管理员编号">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{scope.row.adminCode}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->
            <el-table-column align="center" label="状态">
                <template slot-scope="scope">
                                                <span>

                         <el-tag :type="tagTypes[scope.row.status]">     {{statusOptions[scope.row.status]}}</el-tag>

                        </span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间">
                <template slot-scope="scope">
                    <span>{{parseTime(scope.row.time)}}</span>
                </template>
            </el-table-column>
            <!--            <el-table-column align="center" label="报名结束时间">-->
            <!--                <template slot-scope="scope">-->
            <!--                    <span>{{parseTime(scope.row.endSign)}}</span>-->
            <!--                </template>-->
            <!--            </el-table-column>-->

            <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="warning" v-if="canUpdate" size="mini" @click="sum(scope.row.id)">统计</el-button>
                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope)">编辑</el-button>
                    <el-button v-if="canSave" size="mini" type="danger"
                               @click="handleDelete(scope)">删除
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog title="报名统计" :visible.sync="dialogSumVisible">
            <el-table border :data="sumList" fit>
                <el-table-column align="center" label="名称">
                    <template slot-scope="scope">
                        <span>{{scope.row.name}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                        align="center"
                        label="数量">
                    <template slot-scope="scope">
                        <span>{{scope.row.number}}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>


        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px"
                     style='width: 450px; margin-left:50px;'>
                <!--                <el-form-item label="课程ID" prop="goodsId">-->
                <!--                    <el-input v-model="temp.goodsId"></el-input>-->
                <!--                </el-form-item>-->

                <el-form-item label="课程名" prop="name">
                    <el-input v-model="temp.name"></el-input>
                </el-form-item>

                <el-form-item label="对应商品" prop="goodsId">
                    <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                               v-model="temp.goodsId"
                               placeholder="课程商品">
                        <el-option v-for="(item,index) in  courseList" :key="index" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="开课地址" prop="detail">
                    <el-cascader
                            :props="{value:'text',label:'text'}"
                            v-model="addressValue"
                            :options="addressList"
                            @change="handleAddressChange"></el-cascader>
                </el-form-item>


                <el-form-item label="详细地址" prop="detail">
                    <el-input type="textarea" v-model="temp.detail"></el-input>
                </el-form-item>

                <el-form-item label="开课人数" prop="number">
                    <el-input v-model="temp.number"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="temp.remark"></el-input>
                </el-form-item>
                <el-form-item label="管理员手机号" prop="adminCode">
                    <el-input placeholder="多个英文逗号,隔开" v-model="temp.adminCode"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select class="filter-item" v-model="temp.status" placeholder="状态">
                        <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item"
                                   :value="index">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="开课时间" prop="date">
                    <el-date-picker v-model="temp.time" type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="创建时间">
                    </el-date-picker>
                </el-form-item>
                <!--                <el-form-item label="报名结束时间" prop="date">-->
                <!--                    <el-date-picker v-model="temp.endSign" type="datetime"-->
                <!--                                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="报名结束时间">-->
                <!--                    </el-date-picker>-->
                <!--                </el-form-item>-->
                <el-form-item label="课程图" prop="img">
                    <el-upload
                            ref="imgUpload"
                            action="http://up-z2.qiniup.com"
                            :auto-upload="true"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :before-upload="handleUpload"
                            :on-success="handleimgUploadSuccess"
                            :data="qData"
                            :file-list="imgList"
                            :on-remove="handleimgRemove">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>

                <el-dialog :visible.sync="dialogVisible" append-to-body>
                    <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForm">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
                <el-button v-else type="primary" @click="updateData">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        /*padding-bottom: 20px;*/
    }

    .filter-item {
        margin-bottom: 10px;
    }

    .filter-item.input {
        /*line-height: 60px*/
        margin-right: 10px;
    }
</style>

<script>
    import {list, save, update, remove} from '@/api/course'
    import waves from '@/directive/waves' // 水波纹指令
    import {parseTime} from '@/utils'

    import {getToken, domain} from '@/api/qiniu'
    import {listToStrs, strsToList} from '@/utils/imgUtil'

    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'
    import {all} from "../../../api/mall_goods";
    import {provinceList} from "../../../utils/area";
    import {sum} from "../../../api/course";

    export default {
        name: 'test',
        directives: {
            waves
        },
        data() {
            return {
                sumList: [],
                addressValue: null,
                goodsList: [],
                tableKey: 0,
                list: null,
                total: null,
                listLoading: true,
                time: null
                ,
                endSign: null
                ,
                listQuery: {
                    page: 1,
                    limit: 20,
                    order: 'id desc'
                    ,
                    goodsId: null
                    ,
                    province: null
                    ,
                    city: null
                    ,
                    county: null
                    ,
                    detail: null
                    ,
                    name: null
                    ,
                    number: null
                    ,
                    remark: null
                    ,
                    adminCode: null
                    ,
                    time: null,
                    times: null
                    ,
                    endSign: null,
                    endSigns: null
                    ,
                    status: null
                },
                statusOptions: ["预报名", "确认报名", "已经开课"],
                tagTypes: ['info', '', 'warning', 'danger', 'warning'],
                temp:
                    {
                        id: null,
                        goodsId: null,
                        status: null,
                        province: null,
                        city: null,
                        county: null,
                        detail: null,
                        time: null,
                        endSign: null,
                        name: null,
                        img: null,
                        number: null,
                        remark: null,
                        adminCode: null
                    }
                ,
                dialogFormVisible: false,
                dialogSumVisible: false,
                dialogStatus:
                    '',
                textMap:
                    {
                        update: '修改',
                        create:
                            '新增'
                    }
                ,
                // 存在图片
                dialogImageUrl: '',
                dialogVisible:
                    false,
                imgList: [],
                rules:
                    {
                        goodsId: [
                            {
                                required: true, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        status: [
                            {
                                required: true, message:
                                    '必填字段', trigger:
                                    'blur'
                            }
                        ]
                        ,
                        province: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        city: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        county: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        detail: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        time: [
                            {
                                required: true, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        endSign: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        name: [
                            {
                                required: true, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        img: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        number: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        remark: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                        ,
                        adminCode: [
                            {
                                required: false, message:
                                    '必填字段', trigger:
                                    'change'
                            }
                        ]
                    }
                ,
                downloadLoading: false,
                qData:
                    {
                        token: '',
                        key:
                            ''
                    }
            }
        },
        created() {
            this.getList()
            all().then(res => {
                this.goodsList = res.data
            })
        },
        computed: {
            ...mapGetters([
                'perms'
            ]),
            addressList() {
                return provinceList
            },
            courseList() {
                return this.goodsList.filter(goods => {
                    return goods.name && goods.name.indexOf('课程') > -1

                })
            },
            canSave() {
                return hasAuth(this.perms, 'course:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'course:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'course:update')
            },
            canList() {
                return hasAuth(this.perms, 'course:list')
            }
        },
        methods: {
            sum(courseId) {
                sum(courseId).then(res => {
                    this.sumList = res.data
                    this.dialogSumVisible = true
                })
            },
            handleAddressChange(value) {
                this.temp.province = value[0]
                this.temp.city = value[1]
                this.temp.county = value[2]
            },
            parseTime(time) {
                return parseTime(time, '{y}-{m}-{d}')
            },
            getList() {
                this.listLoading = true
                list(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片
                this.initQiniu()

                // 存在图片字段转换图片地址显示
                this.initImgUrl()
            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
                this.initImgName()// 图片转换
            },
            resetTemp(row) {
                this.addressValue = []
                this.temp = {}
                if (row) {
                    this.temp = Object.assign({}, row) // copy obj
                    this.addressValue = [this.temp.province, this.temp.city, this.temp.county]
                }

            },
            handleCreate() {
                this.beforeFormShow()
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(scope) {
                this.index = scope.$index
                // this.beforeFormShow(scope.row)
                // this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData()
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
            // 显示将图片名封装成可以展示状态集合
            initImgUrl() {
                this.imgList = strsToList(this.temp.img, domain)
            },
            // 关闭显示窗口 重置图片地址 防止错乱
            resetImgUrl() {
                this.imgList = []
            },
            // 上传或者更新的时候从图片链接中获取图片名字
            initImgName() {
                this.temp.img = listToStrs(this.imgList)
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData() {
                // const ids = [this.temp.id]
                const ids = [this.list[this.index].id]
                remove({ids: ids}).then(res => {
                    // 从当前队列中移除
                    this.list.splice(this.index, 1)
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            handleUpdate(scope) {
                this.index = scope.$index
                this.beforeFormShow(scope.row)
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            update(this.temp).then(() => {
                                this.list.splice(this.index, 1, this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                // 存在图片
                this.resetImgUrl()
                this.dialogFormVisible = false
            },
            handleDownload() {
                this.downloadLoading = true
                import('@/vendor/Export2Excel').then(excel => {
                    const tHeader = [
                        '序号'
                        ,
                        '课程ID'
                        ,
                        '省'
                        ,
                        '市'
                        ,
                        '县'
                        ,
                        '详细地址'
                        ,
                        '课程名'
                        ,
                        '开课人数'
                        ,
                        '备注'
                        ,
                        '管理员编号'
                        ,
                        '状态'
                        ,
                        '开课时间'
                        ,
                        '报名结束时间'
                    ]
                    const filterVal = ['id'
                        , 'goodsId'
                        , 'province'
                        , 'city'
                        , 'county'
                        , 'detail'
                        , 'name'
                        , 'number'
                        , 'remark'
                        , 'adminCode'
                        ,
                        'status'
                        ,
                        'time'
                        ,
                        'endSign'
                    ]
                    const data = this.formatJson(filterVal, this.list)
                    excel.export_json_to_excel({
                        header: tHeader,
                        data,
                        filename: 'table-list'
                    })
                    this.downloadLoading = false
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                        return v[j]
                    }
                ))
            },
            // 存在图片
            handleUpload(file) {
                this.qData.key = new Date().valueOf() + file.name
            },
            initQiniu() {
                // 获取七牛配置
                getToken().then(res => {
                    this.qData.token = res.data
                }).catch(error => {
                    console.log(error)
                })
            },
            handleimgUploadSuccess(response, file, fileList) {
                this.imgList.push({name: file.response.key, url: domain + file.response.key})
            }
            ,
            handleimgRemove(file, fileList) {
                for (var fn of this.imgList) {
                    if (fn.name === file.name) {
                        this.imgList.splice(this.imgList.indexOf(fn), 1)
                    }
                }
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url
                this.dialogVisible = true
            }
        }
    }
</script>
